/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.basicmodule.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.ConceptName;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Patient;
import org.openmrs.Person;
import org.openmrs.activelist.Allergy;
import org.openmrs.api.context.Context;
import org.openmrs.module.basicmodule.Note;
import org.openmrs.module.basicmodule.NoteService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * This class configured as controller using annotation and mapped with the URL of 'module/basicmodule/basicmoduleLink.form'.
 */
@Controller
@RequestMapping(value = "module/basicmodule/patientSummary.form")
public class PatientSummaryController{
	
	/** Logger for this class and subclasses */
	protected final Log log = LogFactory.getLog(getClass());
	Integer patientId;
	/** Success form view name */
	private final String SUCCESS_PATIENT_SUMMARY = "/module/basicmodule/patientSummary";
	/**
	 * Initially called after the formBackingObject method to get the landing form name  
	 * @return String form view name
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(){
            System.out.println("GET Patient Summary method***************");
		return SUCCESS_PATIENT_SUMMARY;
	}
	
	/**
	 * All the parameters are optional based on the necessity  
	 * 
	 * @param httpSession
	 * @param anyRequestObject
	 * @param errors
	 * @return
	 */
        
	
        
	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(HttpSession httpSession,
	                               @ModelAttribute("anyRequestObject") Object anyRequestObject, BindingResult errors) {
		System.out.println("POST Patient Summary method***************");
		if (errors.hasErrors()) {
			// return error view
		}	
		return SUCCESS_PATIENT_SUMMARY;
	}		
	
        public String getAlert(int patientID)
    {
        String output=new String();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        // IMPORTANT: Save the old System.out!
        PrintStream old = System.out;
        // Tell Java to use your special stream
        System.setOut(ps);  
        // Print some output: goes to your special stream
        org.openmrs.module.basicmodule.DSS.compiler.Compiler compiler = (new org.openmrs.module.basicmodule.DSS.compiler.Compiler("activated.dss",patientID));
        // Put things back
        System.out.flush();
        
        output+=compiler.compileProgram();
        output+="\n"+baos.toString();
        System.setOut(old);                    
        System.out.println("Here getting alert for Patient Dashboard.");
        
        String fullAlert=new String();        
        int end_2=0;
        while (output.indexOf("#PatientSummary#",end_2)!=-1)
        {            
            int start_1=output.indexOf("#PatientSummary#",end_2);
            if ( start_1!=-1)
            {
                int start_2=output.indexOf("$", start_1);
           //     System.out.println(output.substring(start_1, start_2));
                end_2=output.indexOf("$", start_2+1);
                System.out.println(output.substring(start_1, end_2));
                String alert=output.substring(start_2,end_2);
                System.out.println(alert);
                alert=alert.replace("$", "");       
                alert=alert.toUpperCase();
                fullAlert+= "<p><font color=\"red\" size=\"3\">ALERT : "+alert+"</font></p>";                               
            }            
        }
        return fullAlert;
 }
        @ModelAttribute("patientsummary")
	protected String[] formBackingObject(HttpServletRequest request) throws Exception {
            // This methode should have returned a singla object - it would have been better to
            // return a mapping via model/view
            String output[]=new String[10];
            String patientIdStr= (String) request.getParameter("patientId");
            Integer patientId = Integer.valueOf(patientIdStr);
            Patient p = Context.getPatientService().getPatient(patientId);               
            
            
//            System.out.println("Person Id= "+p.getPersonId());
//            Person person=Context.getPersonService().getPerson(p.getPersonId());
//            List<Allergy> allergies=Context.getPatientService().getAllergies(person);
//            System.out.println("Here in form backing "+person.getGivenName()+"Size "+allergies.size());
//            Allergy a2=Context.getPatientService().getAllergy(patientId);
//            System.out.println("Direct"+a2.toString());
//            System.out.println("Here in form backing1 "+a2.getAllergen().getName().getName());
//            Allergy a1=allergies.get(0);
//            System.out.println("Here in form backing2");
//            Concept cc=a1.getAllergen();
//            System.out.println("Allergy 1 from concept: "+cc.getName().getName());
//            System.out.println("Allergy 1: "+a1.toString());
            
            
            
            String gender=(p.getGender().compareTo("M")==0) ?"Male":"Female";            
            output[0]="Name : "+p.getGivenName()+"<br>"+"Gender : "+gender+"<br>Age : "+p.getAge()+"<br>Address:<br>"
                    +p.getPersonAddress().getAddress1()+"<br>"+p.getPersonAddress().getAddress2()+"<br>"+p.getPersonAddress().getCityVillage()+"<br>"+p.getPersonAddress().getStateProvince()+"<br>"+p.getPersonAddress().getCountry()+"<br>";
            
            
            
            List<Encounter> allEncounters= Context.getEncounterService().getEncountersByPatient(p);
            double weight[]=new double[2];
            double d_bp[]=new double[2];
            double s_bp[]=new double[2];
            double temperature[]=new double[2];
            double score[]=new double[2];
            double cd4 = 0;
            double hemo = 0;
            Date date[]=new Date[2];
            int i,j,k,l,m,n,o;
            i=j=k=l=m=n=o=0;
            String who=new String();
            String vload=new String();
            String regimen=new String();
            String sulpha=new String();
            String pen=new String();
            String other=new String();
            
            String location=new String();
            if (allEncounters.size()!=0)
            {
                Encounter e=allEncounters.get(0);
                location=e.getLocation().getName();
            }
            output[0]+="Clinic Location : "+ location+"<br>";
            
            for (Encounter encounter:allEncounters)
            {
            if (i<allEncounters.size())
            {
                System.out.println("Here In ENcounter ");
                Set<Obs> allEncounterObs = encounter.getAllObs();                
                date[(n++)%2]=encounter.getEncounterDatetime();                
                for (Obs obs:allEncounterObs)
                {                                                    
                    int temp=obs.getConcept().getConceptId().intValue();
                    System.out.println(temp);
                    switch (temp)
                    {
                        case 5089 : weight[(j++)%2]=obs.getValueNumeric();
                                    break;
                        case 5088 : temperature[(k++)%2]=obs.getValueNumeric();
                                    break;
                        case 5085 : s_bp[(l++)%2]=obs.getValueNumeric();
                                    break;
                        case 5086 : d_bp[(m++)%2]=obs.getValueNumeric();
                                    break;                                        
                        case 5283 : score[(o++)%2]=obs.getValueNumeric();
                                    break;    
                        case 5497 : cd4=obs.getValueNumeric();    
                                    break;
                        case 5356 : who=obs.getValueCoded().getDisplayString();                                    
                                    break;    
                        case 21 :    hemo=obs.getValueNumeric();    
                                    break;
                        case 1305 : vload=obs.getValueCoded().getDisplayString();
                                    break;
                        case 1088 : regimen+=obs.getValueCoded().getDisplayString()+", ";
                                    break; 
                        case 6012 : System.out.println(obs.getConcept().getName().getName());
                                    sulpha=obs.getConcept().getName().getName();
                                    break;  
                        case 6011 : System.out.println(obs.getConcept().getName().getName());
                                    pen=obs.getConcept().getName().getName();
                                    break;  
                        case 1083 : System.out.println(obs.getConcept().getName().getName());
                                    other=obs.getConcept().getName().getName();
                                    
                                    break;  
                            
                    }
                }                                        
                    i++;
                                
            }
            
            
            
	}
            
            output[1]="<table border=\"1\"><tr><td>Encounter Date</td><td>Weight</td><td>Temperature</td><td>Blood Pressure</td><td>Karnofsky Score</td></tr>";
            for (i=0;i<date.length;i++)
               output[1]+="<tr><td>"+date[i]+"</td><td>"+weight[i]+"</td><td>"+temperature[i]+"</td><td>"+d_bp[i]+"/"+s_bp[i]+"</td><td>"+score[i]+"</td></tr>";
            output[1]+="</table>";        
            output[2]="HIV WHO Stage : "+who+"<br>";
            output[2]+="Allergies : "+sulpha+" "+pen+" "+other+"<br>";
            output[2]+="ART Drugs Regimen : "+regimen+"<br>";
            output[3]="<table border=\"1\"><tr><td>Laboratory Result</td></tr><tr><td>CD4 Count</td><td>Hemoglobin</td><td>Viral Load</td></tr>"
                    +"<tr><td>"+cd4+"</td><td>"+hemo+"</td><td>"+vload+"</td></tr></table>";
            output[4]=getAlert(patientId);
           return output;     
    }
}